import {
  Avatar,
  Box,
  Button,
  Dialog,
  DialogActions,
  DialogContent,
  DialogContentText,
  DialogTitle,
  Divider,
  ListItem,
  ListItemAvatar,
  ListItemText,
  List,
  Paper,
  Select,
  MenuItem,
} from "@mui/material";
import Face4Icon from "@mui/icons-material/Face4";
import BookmarkAddedIcon from "@mui/icons-material/BookmarkAdded";
import PinDropIcon from "@mui/icons-material/PinDrop";
import AutoStoriesIcon from "@mui/icons-material/AutoStories";
import ComputerIcon from "@mui/icons-material/Computer";
import React from "react";
import AccessAlarmsIcon from "@mui/icons-material/AccessAlarms";
import { useState } from "react";
import { Chip, Grid, Typography, useTheme } from "@mui/material";
import { green, grey, purple, red, yellow } from "@mui/material/colors";
import { useMemo } from "react";
import { useContext } from "react";
import { useEffect } from "react";
import CourseCard from "../../../components/CourseCard";
import { TitleContext } from "../../../router";
import "./SelectCourse.css";
import FindFail from "../../../components/FindFail";
import { useMutation } from "@tanstack/react-query";
import { postQueryFn } from "../../../query/postQueryFn";
import {
  SELECT_COURSE_LIST_URL,
  SELECT_COURSE_URL,
} from "../../../constants/url";
import Loading from "../../../components/loading";
import SearchAppBar from "../../../components/AppbarSearch";
import { mutateQueryFn } from "../../../query/mutateQueryFn";
import { useSnackbar } from "notistack";
import ConfirmDialog from "../../../components/ConfirmDialog";
let staSchedule = [
  [[], [], [], [], [], [], []],
  [[], [], [], [], [], [], []],
  [[], [], [], [], [], [], []],
  [[], [], [], [], [], [], []],
  [[], [], [], [], [], [], []],
];

const numChan = ["一", "二", "三", "四", "五"];
const columnTitle = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"];
const colors = ["#f9f6f680", "#c9c9c940"];

export default function SelectCourse() {
  const nowTitle = useContext(TitleContext);
  useEffect(() => {
    nowTitle.setnowTitle(3);
  });
  const [choseType, setChoseType] = useState("不限");
  const [choseState, setChoseState] = useState("不限");
  const [searchName, setSearchName] = useState("");

  useEffect(() => {
    courseMutate({
      Key: [SELECT_COURSE_LIST_URL, { useToken: true }],
      method: "get",
    });
  }, []);

  const {
    data,
    isSuccess: courseSuccess,
    isError: courseError,
    isLoading: courseLoading,
    mutate: courseMutate,
  } = useMutation(["selectedCourse"], postQueryFn);

  const {
    //选课接口
    isSuccess: selSuccess,
    isError: selError,
    isLoading: selLoading,
    mutate: selMutate,
  } = useMutation(["selectCourse"], mutateQueryFn);
  const handleChangeSearchName = (e) => {
    setSearchName(e.target.value);
  };

  const check = (e) => {
    if (
      searchName != "" &&
      searchName != null &&
      e?.name.search(searchName) == -1
    )
      return false;
    if (choseType !== "不限" && choseType != e?.type) return false;
    let tmp = e?.isSelected ? "已选" : "未选";
    if (choseState !== "不限" && choseState !== tmp) return false;

    return true;
  };

  const count = () => {
    for (var i in data.data.data) {
      if (check(data.data.data[i])) return false;
    }
    return true;
  };

  const handleSelect = (e) => {
    //e传回课程id
    selMutate({
      url: SELECT_COURSE_URL,
      params: { course: e },
      method: "put",
      useToken: true,
    });
  };
  const handleDel = (e) => {
    selMutate({
      url: SELECT_COURSE_URL,
      params: { course: e },
      method: "delete",
      useToken: true,
    });
  };

  const { enqueueSnackbar } = useSnackbar();
  useEffect(() => {
    if (selSuccess) {
      enqueueSnackbar("操作成功", { variant: "success" });
      courseMutate({
        Key: [SELECT_COURSE_LIST_URL, { useToken: true }],
        method: "get",
      });
    }

    if (selError) {
      enqueueSnackbar("操作失败", { variant: "error" });
    }
  }, [selSuccess]);

  /* 
   下面是前端构造出的课表，后端应返回散列的课表。
   对散列课表进行状态管理，选课是修改散列课表。
   监听散列课表变化，改变构造出的课表
  */

  return (
    <div>
      {courseSuccess && data.data.data.length == 0 && (
        <Box
          sx={{
            padding: 10,
            display: "flex",
            flexDirection: "column",
            justifyContent: "center",
            alignItems: "center",
          }}
        >
          <FindFail text="" />
          <Typography variant="h4" color="primary">
            当前不在任何选课时间段
          </Typography>
        </Box>
      )}
      <Grid container spacing={3}>
        <Grid item lg={8} md={12} xs={12}>
          {courseLoading && <Loading />}
          {courseSuccess && data.data.data.length != 0 && (
            <Schedule data={data.data.data} />
          )}
        </Grid>
        <Grid
          item
          sx={{ maxHeight: "calc(100vh - 100px)" }}
          lg={4}
          md={12}
          xs={12}
        >
          {courseLoading && <Loading />}
          {courseSuccess && !courseLoading && data.data.data.length != 0 && (
            <Paper sx={{ padding: 3, height: "100%", overflow: "hidden" }}>
              <Box
                sx={{
                  display: "flex",
                  flexWrap: "wrap",
                  flexDirection: "row",
                  // marginTop: "3px",
                  alignItems: "center",
                }}
              >
                <Select
                  value={choseState}
                  onChange={(e) => {
                    setChoseState(e.target.value);
                  }}
                  size="small"
                  sx={{ marginRight: 2 }}
                >
                  <MenuItem value={"不限"}>不限</MenuItem>
                  <MenuItem value={"已选"}>已选</MenuItem>
                  <MenuItem value={"未选"}>未选</MenuItem>
                </Select>
                <Select
                  value={choseType}
                  onChange={(e) => {
                    setChoseType(e.target.value);
                  }}
                  size="small"
                >
                  <MenuItem value={"不限"}>不限</MenuItem>
                  <MenuItem value={"必修"}>必修</MenuItem>
                  <MenuItem value={"选修"}>选修</MenuItem>
                  <MenuItem value={"限选"}>限选</MenuItem>
                </Select>
                <Box flexGrow={1} />
                <Box>
                  <SearchAppBar
                    name={searchName}
                    handleChange={handleChangeSearchName}
                  />
                </Box>
              </Box>

              <Box
                className="scrollBox"
                sx={{
                  maxHeight: "calc(100vh - 205px)",
                  marginTop: "10px",
                  overflow: "auto",
                  paddingTop: "3px",
                }}
              >
                {data.data.data.map((value) => {
                  return (
                    check(value) && (
                      <ChoseCard
                        handleClick={
                          !value?.isSelected ? handleSelect : handleDel
                        }
                        course={value}
                      />
                    )
                  );
                })}
                {count() && <FindFail />}
              </Box>
            </Paper>
          )}
        </Grid>
      </Grid>
    </div>
  );
}

const ChoseCard = (props) => {
  const [open, setOpen] = useState(false);
  // const handleClose = ()
  const [confirmOpen, setConfirmOpen] = useState(false);
  return (
    <>
      <ConfirmDialog
        text={
          "你确定要" +
          (props.course?.isSelected ? "退选" : "选择") +
          props.course.name +
          "吗?"
        }
        open={confirmOpen}
        handleClose={() => setConfirmOpen(false)}
        handleConfirm={() => props.handleClick(props.course.id)}
      />
      <Dialog
        open={open}
        onClose={() => {
          setOpen(false);
        }}
        aria-labelledby="alert-dialog-title"
        aria-describedby="alert-dialog-description"
      >
        <DialogTitle id="alert-dialog-title">{props.course.name}</DialogTitle>
        <DialogContent>
          <DialogContentText id="alert-dialog-description">
            <List>
              <ListItem>
                <ListItemAvatar>
                  <Avatar
                    sx={{ color: "common.white", bgcolor: "primary.main" }}
                  >
                    <AccessAlarmsIcon
                    // color="white"
                    // color="primary"
                    // sx={{ background: "red" }}
                    />
                  </Avatar>
                </ListItemAvatar>
                <ListItemText
                  sx={{ minWidth: 300 }}
                  primary={
                    "上课日期: 第" +
                    props.course.time.weeks?.map((value, key) => {
                      return value;
                    }) +
                    "周"
                  }
                />
              </ListItem>
              <Divider />
              <ListItem>
                <ListItemAvatar>
                  <Avatar
                    sx={{ color: "common.white", bgcolor: "primary.main" }}
                  >
                    <AutoStoriesIcon />
                  </Avatar>
                </ListItemAvatar>
                <ListItemText
                  sx={{ minWidth: 300 }}
                  primary={"课序号: " + props.course.courseId}
                  // secondary={props.teacher}
                />
              </ListItem>
              <Divider />
              <ListItem>
                <ListItemAvatar>
                  <Avatar
                    sx={{ color: "common.white", bgcolor: "primary.main" }}
                  >
                    <Face4Icon />
                  </Avatar>
                </ListItemAvatar>
                <ListItemText
                  sx={{ minWidth: 300 }}
                  primary={"上课老师: " + props.course.teacher}
                  // secondary={props.teacher}
                />
              </ListItem>
              <Divider />
              <ListItem>
                <ListItemAvatar>
                  <Avatar
                    sx={{ color: "common.white", bgcolor: "primary.main" }}
                  >
                    <PinDropIcon />
                  </Avatar>
                </ListItemAvatar>
                <ListItemText
                  sx={{ minWidth: 300 }}
                  primary={"上课地点: " + props.course.location}
                  // secondary={props.teacher}
                />
              </ListItem>{" "}
              <Divider />
              <ListItem>
                <ListItemAvatar>
                  <Avatar
                    sx={{ color: "common.white", bgcolor: "primary.main" }}
                  >
                    <ComputerIcon />
                  </Avatar>
                </ListItemAvatar>
                <ListItemText
                  sx={{ minWidth: 300 }}
                  primary={"课程类型: " + props.course?.type}
                  // secondary={props.teacher}
                />
              </ListItem>
              <Divider />
              <ListItem>
                <ListItemAvatar>
                  <Avatar
                    sx={{ color: "common.white", bgcolor: "primary.main" }}
                  >
                    <BookmarkAddedIcon />
                  </Avatar>
                </ListItemAvatar>
                <ListItemText
                  sx={{ minWidth: 300 }}
                  primary={"学分: " + props.course.credit}
                  // secondary={props.teacher}
                />
              </ListItem>
            </List>
          </DialogContentText>
        </DialogContent>
        <DialogActions>
          <Button
            variant="outlined"
            onClick={() => {
              setOpen(false);
            }}
          >
            知道了
          </Button>
        </DialogActions>
      </Dialog>
      <Paper
        elevation={4}
        sx={{
          borderRadius: 3,
          marginBottom: 3,
          padding: 2,
          marginLeft: "2px",
          marginRight: "2px",
        }}
      >
        <Box
          onClick={() => {
            setOpen(true);
          }}
          sx={{
            cursor: "pointer",
            display: "flex",
            flexDirection: "row",
            alignItems: "center",
          }}
        >
          <Typography
            color="primary"
            sx={{ fontWeight: "bold", cursor: "pointer" }}
          >
            {props.course.name}
          </Typography>
          <Box flexGrow={1} />
          <Chip
            label={props.course?.isSelected ? "已选" : "未选"}
            color={props.course?.isSelected ? "error" : "info"}
            variant="outlined"
          ></Chip>
        </Box>
        <Box
          onClick={() => {
            setOpen(true);
          }}
          sx={{
            cursor: "pointer",
          }}
        >
          <Typography sx={{ cursor: "pointer" }}>
            {props.course.teacher}
          </Typography>
        </Box>

        <Box
          sx={{
            marginTop: 1,
            display: "flex",
            flexDirection: "row",
            alignItems: "center",
          }}
        >
          <Chip
            label={props.course.type ?? "其他"}
            variant="outlined"
            // color="primary"
          ></Chip>
          <Chip
            sx={{ marginLeft: 1 }}
            label={
              "课容量 " + props.course.selected + "/" + props.course.capacity
            }
            variant="outlined"
            // color="primary"
          ></Chip>
          <Box
            onClick={() => {
              setOpen(true);
            }}
            flexGrow={1}
          />
          <Button
            variant="contained"
            onClick={() => setConfirmOpen(true)}
            color={props.course?.isSelected ? "error" : "info"}
          >
            {props.course?.isSelected ? "退选" : "选课"}
          </Button>
        </Box>
      </Paper>
    </>
  );
};

const Schedule = (props) => {
  const [schedule, setSchedule] = useState();
  useEffect(() => {
    for (var i = 0; i < 5; ++i) {
      for (var j = 0; j < 7; ++j) {
        staSchedule[i][j].length = 0;
      }
    }

    for (var ii in props.data) {
      var i = props.data[ii];
      if (i?.isSelected) {
        for (var jj in i.time.order) {
          var j = i.time.order[jj];
          var k = i.time.weekday[jj];
          staSchedule[j - 1][k - 1].push(i);
        }
      }
    }
    setSchedule(staSchedule);
  }, []);
  const theme = useTheme();
  return (
    <Paper
      sx={{
        display: "flex",
        justifyContent: "center",
        flexDirection: "row",
      }}
    >
      <Box
        sx={{
          width: "100%",
          display: "flex",
          flexDirection: "column",
        }}
      >
        <Box
          sx={{
            width: "100%",
            display: "flex",
            flexDirection: "row",

            boxShadow: "rgb(0 0 0 / 30%) 0px 3px 2px",
          }}
        >
          <Box
            sx={{ width: "5.5%", height: "50px", background: colors[1] }}
          ></Box>

          {columnTitle.map((value) => {
            return (
              <Box
                sx={{
                  borderLeft: "1px solid #e1d8d861",
                  width: "13.5%",
                  justifyContent: "center",
                  height: "50px",
                  display: "flex",
                  flexDirection: "column",
                  background:
                    theme.palette.mode == "dark" ? grey[800] : colors[0],
                  alignItems: "center",
                }}
              >
                {value}
              </Box>
            );
          })}
        </Box>
        {schedule?.map((value, key) => {
          return (
            <Box
              sx={{
                flexDirection: "row",
                width: "100%",
                display: "flex",
              }}
            >
              <Box
                sx={{
                  width: "5.5%",
                  display: "flex",
                  flexDirection: "column",
                  justifyContent: "center",
                  alignItems: "center",
                  height: "auto",
                  aspectRatio: "5/7",
                  border: "1px solid #e1d8d861",
                  background:
                    theme.palette.mode == "dark" ? grey[800] : colors[0],
                }}
              >
                <p>
                  第<br />
                  {numChan[key]}
                  <br />节
                </p>
              </Box>
              {value?.map((val2, k1) => {
                return (
                  <Box
                    sx={{
                      width: "13.5%",
                      justifyContent: "center",
                      height: "auto",
                      aspectRatio: "1.2",
                      display: "flex",
                      flexDirection: "column",
                      alignItems: "center",
                      border: "1px solid #e1d8d861",
                    }}
                  >
                    {/* <p>{val2[0]?.name}</p> */}
                    {val2?.map((val3, k2) => {
                      return (
                        <CourseCard
                          sch={val3}
                          color={(key * 7 + k1 * 3 + k2) % 12}
                          length={val2.length}
                        />
                      );
                    })}
                  </Box>
                );
              })}
            </Box>
          );
        })}
      </Box>
    </Paper>
  );
};
